﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Windows_Game_01
{
    public class TileSheet
    {
        private class TileData
        {
            public int ID = -1;
            public Texture2D texture = null;
            public string FileName = "";

            internal void Load(ContentManager Content)
            {
                texture = Content.Load<Texture2D>(FileName);
            }

            internal void Unload()
            {
                texture = null;
            }
        };
        private ContentManager Content;
        private int Width;
        private int Height;

        Dictionary<int, TileData> TextureList = new Dictionary<int, TileData>();

        int[,] Tiles;

        public TileSheet(ContentManager Content, int Width, int Height)
        {
            this.Width = Width;
            this.Height = Height;
            this.Content = Content;
            Tiles = new int[Width, Height];
            Random rand = new Random();
            for (int y = 0; y < Height; y++)
            {
                for (int x = 0; x < Width; x++)
                {
                    Tiles[y, x] = rand.Next() % 2;
                }
            }
        }
        public void RegisterTexture(string texture, int index)
        {
            TextureList.Add(index, new TileData() { ID = index, FileName = texture });
        }

        bool IsLoaded = false;

        public void DrawSheet(SpriteBatch spriteBatch)
        {
            spriteBatch.Begin();

            if(IsLoaded)
            {
                for (int y = 0; y < Height; y++)
                {
                    for (int x = 0; x < Width; x++)
                    {
                        spriteBatch.Draw(TextureList[Tiles[y, x]].texture, new Vector2(x * 20, y * 20), Color.White);
                    }
                }
            }

            spriteBatch.End();

        }


        public void Load()
        {
            IsLoaded = true;
            foreach (var item in TextureList.Values)
            {
                item.Load(Content);
            }
        }

        public void Unload()
        {
            IsLoaded = false;
            foreach (var item in TextureList.Values)
            {
                item.Unload();
            }
        }
    }
}